package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;//日志

    @Autowired
    private AnalysisMapper analysisMapper; //统计

    /**
     * 定时统计
     *  业务：查询tb_log表中的数据，保存或者更新到tb_analysis表中
     */
    public void analysis() throws ParseException {

        //获取时间
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //2021-08-03
        String yesterdayStr =  DateUtil.yesterday().toString("yyyy-MM-dd"); //工具类
        //1、调用mapper根据要求查询数据
        //1.1 新注册用户数
        Integer logNum = logMapper.queryByTypeAndLogTime("0102", todayStr);
        //1.2 活跃用户数
        Integer actNum = logMapper.queryByLogTime(todayStr);
        //1.3 登陆次数
        Integer regNum = logMapper.queryByTypeAndLogTime("0101", todayStr);
        //1.4 次日留存用户数
        Integer mumRetention1d = logMapper.queryMumRetention1d(todayStr, yesterdayStr);
        //2、根据日期查询统计数据
        Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(todayStr);
        QueryWrapper<Analysis> qw = new QueryWrapper<>();
        qw.eq("record_date",recordDate);
        Analysis analysis = analysisMapper.selectOne(qw);
        //2.1 如果数据不存在，保存
        if(analysis == null) {
            analysis = new Analysis();
            analysis.setNumRetention1d(mumRetention1d);
            analysis.setNumLogin(logNum);
            analysis.setNumRegistered(regNum);
            analysis.setNumActive(actNum);
            analysis.setRecordDate(recordDate);
            analysis.setCreated(new Date());
            analysisMapper.insert(analysis);
        }else {
            //2.2 数据存在的话，更新
            analysis.setNumRetention1d(mumRetention1d);
            analysis.setNumLogin(logNum);
            analysis.setNumRegistered(regNum);
            analysis.setNumActive(actNum);
            analysisMapper.updateById(analysis);
        }
    }
}
